package com.rms.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rms.entity.DinnerTable;
import com.rms.entity.Food;
import com.rms.entity.OrderDetail;
import com.rms.entity.Orders;
import com.rms.utils.PageBean;
import com.rms.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping(value = "/order")
public class OrderAction extends BaseAction{



	//放入购物车
	@RequestMapping(value = "/putInCar")
	public String putInCar(String food_id,HttpServletRequest request,
			HttpServletResponse response)  {
		HttpSession session = request.getSession();

		Map<Food, Integer> map = new LinkedHashMap<Food, Integer>();

		// 获取食物id
		Food food = foodService.findById(Integer.parseInt(food_id));
		
		//用于存储订单数据
		Map<Food, Integer> m = (Map<Food, Integer>) session
				.getAttribute("foods");

		if (m != null) {
			if (m.containsKey(food)) {
				Integer count = m.get(food);
				count++;
				m.put(food, count);
			} else {
				m.put(food, 1);
			}
		} else {
			map.put(food, 1);
		}

		if (m != null) {
			session.setAttribute("foods", m);
		} else {
			session.setAttribute("foods", map);
		}


		return "redirect:/app/detail/clientCart.jsp";
	}

	//删除订单
	@RequestMapping(value = "/removeOrder")
	public Object removeOrder(int gid,HttpServletRequest request,
			HttpServletResponse response){


		Food food = foodService.findById(gid);
		HttpSession session = request.getSession();
		
		//获取加入餐车时的食物数据
		Map<Food, Integer> m = (Map<Food, Integer>) session
				.getAttribute("foods");
		m.remove(food);
		session.setAttribute("foods", m);

		return "redirect:/app/detail/clientCart.jsp";
	}

	@RequestMapping(value = "/alterSorder")
	public String alterSorder(int gid,HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {


		Food food = foodService.findById(gid);

		// 获取修改狗的数量
		String num = request.getParameter("snumber");
		HttpSession session = request.getSession();
		Map<Food, Integer> m = (Map<Food, Integer>) session
				.getAttribute("foods");
		m.put(food, Integer.parseInt(num));
		session.setAttribute("foods", m);


		return "redirect:/app/detail/clientCart.jsp";
	}

	//下单的方法
	@RequestMapping(value = "/takeOrder")
	public String takeOrder(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {


		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		Map<Food, Integer> m = (Map<Food, Integer>) session
				.getAttribute("foods");
		String table_id = (String) session.getAttribute("table_id");

		// 新建订单对象
		Orders order = new Orders();
		order.setTable_id(Integer.parseInt(table_id));

		Set<Entry<Food, Integer>> entrySet = m.entrySet();
		// 创建订单详细对象
		OrderDetail detail = new OrderDetail();

		// 定义总价钱
		int sum = 0;
		int orderId = ordersService.getCount() + 1;

		for (Entry<Food, Integer> entry : entrySet) {
			Food food = entry.getKey();
			Integer count = entry.getValue();
			order.setId(food.getId());
			sum += food.getPrice() * count;
			order.setOrderDate(new Date());
		}

		order.setTotalPrice(sum);
		ordersService.add(order);

		for (Entry<Food, Integer> entry : entrySet) {
			Food food = entry.getKey();
			Integer count = entry.getValue();
			detail.setFood_id(food.getId());
			detail.setOrderId(orderId);
			detail.setFoodCount(count);
			orderDetailService.add(detail);
		}

		findOrder(request);


		return "redirect:/app/detail/clientOrderList.jsp";
	}

	public void findOrder(HttpServletRequest request){
		List<Orders> orders = ordersService.query();
		List<OrderDetail> orderDetail = orderDetailService.query();
		request.getServletContext().setAttribute("orders", orders);
		request.getServletContext().setAttribute("orderDetail", orderDetail);
	}

	@RequestMapping(value = "/showOrderDetail")
	public Object showOrderDetail(String orderId,HttpServletRequest request)  {


		List<OrderDetail> list = null;
		if (orderId != null && !orderId.isEmpty()) {
			list = orderDetailService.findByOrderId(Integer.parseInt(orderId));
		}
		request.setAttribute("orderDetail", list);
		return "/sys/order/orderDetail.jsp";
	}

	// 后台结账的方法
	@RequestMapping(value = "/pay")
	public String pay(String currentPage,int orderId,String tableId,HttpServletRequest request)
			throws ServletException, IOException {

		Orders o = new Orders();
		o.setOrderStatus(1);
		o.setId(orderId);

		ordersService.update(o);


		if (!StringUtils.isNull(tableId)) {
			dinnerTableService.quitTable(Integer.parseInt(tableId));
		}
		findOrder(request);

		DinnerTable table = dinnerTableService.findById(Integer.parseInt(tableId));// 用于后台点击结账时消除通知
		@SuppressWarnings("unchecked")
		List<String> list = (List<String>) request.getServletContext()
				.getAttribute("tn");
		if (list != null) {
			list.remove(table.getTableName());
		}

		// 5. 跳转
		return list(currentPage,request);


	}

	// 前台呼叫结账的方法
	@RequestMapping(value = "/call")
	public Object call(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Object uri = null;
		HttpSession session = request.getSession();
		String id = (String) session.getAttribute("table_id");
		DinnerTable table = dinnerTableService.findById(Integer.parseInt(id));

		Map<Food, Integer> m = (Map<Food, Integer>) session
				.getAttribute("foods");

		if(m!=null){
			m.clear();
		}

		String tableName = table.getTableName();

		@SuppressWarnings("unchecked")
		List<String> tab = (List<String>) request.getServletContext()
				.getAttribute("tn");
		if (tab == null) {
			tab = new ArrayList<String>();
		}
		tab.add(tableName);

		request.getServletContext().setAttribute("tn", tab);

		List<DinnerTable> tables = dinnerTableService.query();// 更新前台首页的桌子
		request.getServletContext().setAttribute("table", tables);



		return "redirect:/app/index.jsp";
	}

	@RequestMapping(value = "/list")
	public String list(String currentPage,HttpServletRequest request){

		// 1. 获取“当前页”参数； (第一次访问当前页为null)

		// 判断
		if (currentPage == null || "".equals(currentPage.trim())) {
			currentPage = "1"; // 第一次访问，设置当前页为1;
		}
		// 转换
		int currentPageI = Integer.parseInt(currentPage);

		// 2. 创建PageBean对象，设置当前页参数； 传入service方法参数
		PageBean<Orders> pageBean = new PageBean<Orders>();
		pageBean.setCurrentPage(currentPageI);
		pageBean.setPageCount(6);

		// 3. 调用service
		ordersService.getAll(pageBean); // 【pageBean已经被dao填充了数据】
		// 4. 保存pageBean对象，到request域中
		request.setAttribute("pageBean", pageBean);

		// 5. 跳转
		return "/sys/order/orderList.jsp";
	}
}
